package com.agp.test.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Produce implements Runnable{

    private Lock lock = new ReentrantLock();
    private Boolean flag = false;
    private Condition condition = lock.newCondition();
    private int number = 1;

    public Produce(Lock lock, Boolean flag) {
        this.lock = lock;
        this.flag = flag;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        lock.lock();
        try {
            while (flag == true) {
                //等待消费者消费完毕
                condition.await();

                System.out.println("接收到生产通知,开始生产");
            }

            System.out.println(Thread.currentThread().getName() + "-----生产-----");
            number++;
            System.out.println("number: " + number);
            TimeUnit.MILLISECONDS.sleep(1000);

            flag = true;

            //通知进行消费
            condition.signalAll();

        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
